import { Instrusion } from "@/Battle/Intrusion.js";

import CombatEventBus from "@/Battle/CombatEventBus.js";
import { BattleEventType } from "@/Battle/Event/BattleEvent.js";

class _AutoInput extends Instrusion {
    constructor() {super();}
    onload(){
        CombatEventBus.on(
            BattleEventType.Action.Prepare.Request,
            this.onActionAutoInput
        );
    }

    onActionAutoInput = (event) => {
        let action = event.payload.action;
        if (!action.hasSelected()) {
            let subject = action.subject();
            if (subject.isConfused()) {
                action.setConfusion();
            } else if (subject.isActor()) {
                let skills=subject.getSkillLists();
                let maxValue = Number.MIN_VALUE;
                let id=1;
                for(let skill of skills){
                    action.setSkill(skill.id);
                    let value = action.evaluate();
                    if (value > maxValue) {
                        maxValue = value;
                        id=skill.id;
                    }
                }
                action.setSkill(id);
            } else if (subject.isEnemy()) {
                let behaviors = subject.getSkillLists();
                if (!behaviors) event.reject(this);
                let ratingMax=0;
                for(let behavior of behaviors){
                    if(behavior.rating>ratingMax){
                        ratingMax=behavior.rating;
                    }
                }
                let ratingZero = ratingMax - 3;
                behaviors = behaviors.filter(a=>a.rating > ratingZero);
                let behavior=subject.selectAction(behaviors, ratingZero);
                action.setSkill(behavior?.skillId??subject.attackSkillId());
            }

            action.makeTargets();
        }

    }

    onunload(){
        AutoInput.onlyInput=null;
        CombatEventBus.off(
            BattleEventType.Action.Prepare.Request,
            this.onActionAutoInput
        );
    }
}

export class AutoInput {
    /**
     * @type { _AutoInput }
     */
    static onlyInput = null;
    constructor() {
        if (!AutoInput.onlyInput) {
            AutoInput.onlyInput = new _AutoInput();
        }
        return AutoInput.onlyInput;
    }
}